//
//  ViewController.m
//  client100
//
//  Created by 孙晓晔 on 2017/5/15.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "ViewController.h"
#import "MySocket.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *host; // 主机
@property (weak, nonatomic) IBOutlet UITextField *port; // 端口

@property (weak, nonatomic) IBOutlet UILabel *showText; // 显示状态
@property (weak, nonatomic) IBOutlet UILabel *userText;

@property (weak, nonatomic) IBOutlet UITextField *inputText; // 待发送消息

@property (weak, nonatomic) IBOutlet UIButton *connectBtn; // 连接
@property (weak, nonatomic) IBOutlet UIButton *disconnectBtn; // 断开
@property (weak, nonatomic) IBOutlet UIButton *sendBtn; // 发送

@property (weak, nonatomic) IBOutlet UITextField *nickname; // 昵称
@property (weak, nonatomic) IBOutlet UITextField *toUser; // 聊天对像

@property(nonatomic,strong) MySocket *socket; // 通讯套接字

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.connectBtn.enabled = TRUE;
    self.sendBtn.enabled = FALSE;
    self.disconnectBtn.enabled = FALSE;
    
    [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:TRUE block:^(NSTimer * _Nonnull timer) {
        
        if (self.socket.isConnected) {
            self.connectBtn.enabled = FALSE;
            self.sendBtn.enabled = TRUE;
            self.disconnectBtn.enabled = TRUE;
            
            self.userText.text = [self.socket stringUserList];
            NSString *str = [self.socket msgList];
            
            NSLog(@"%@", str);
            self.showText.text = str;
            
        } else {
            self.connectBtn.enabled = TRUE;
            self.sendBtn.enabled = FALSE;
            self.disconnectBtn.enabled = FALSE;
        }
        
    }];
}

// 懒加载
-(MySocket *)socket {
    if (_socket == nil) {
        
        NSString *host = self.host.text;
        NSString *port = self.port.text;
        
        _socket = [[MySocket alloc]initWithHostPort:host port:[port intValue]];
        
    }
    
    return _socket;
}

// 连接
- (IBAction)connect:(id)sender {
    
    self.socket.nickname = self.nickname.text;
    
    dispatch_queue_t queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(queue1, ^{
        [self.socket createSockect];
    });
}

// 断开连接
- (IBAction)disconnect:(id)sender {
    
    [self.socket close];
}

// 发送消息
- (IBAction)send:(id)sender {
    
    NSString *str = self.inputText.text;
    NSString *to = self.toUser.text;
    
    [self.socket chat:to body:str];
    
    self.inputText.text = @"";
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"touches began");
    
    [self.inputText resignFirstResponder];
}
@end
